﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Linq.Expressions;
using System.Text;

namespace EventbriteService
{
    internal static class MapperExtensions
    {

        public static bool IsNullable(this PropertyInfo target)
        {
            return target.PropertyType.IsGenericType && target.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
        }
        
        public static PropertyInfo FindPropertyForElement(this Type target, string name)
        {
            var binding =BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
            if (name.Equals("user_id"))
                name = name.Split('_')[1];
            return target.GetProperty(ConvertToMemberName(name), binding );
        }

        public static string MemberName(this XName target)
        {
            return ConvertToMemberName(target.LocalName); 
        }

        public static string ConvertToMemberName(this string target)
        {
            if (target.Contains('-'))
            {
               target = target.Replace('-', '_');
                
            }
            
            string result = target;
    
            if (target.Contains('_'))
            {
                result = target.Replace("_", string.Empty);
            }
            else if (target.Contains('.'))
            {
                result = target.Replace(".", string.Empty);
            }

            return result;
        }

        public static Type FindTypeForElement(this PropertyInfo target)
        {
           return  target.PropertyType.IsGenericType && target.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)) ?
                                                   Nullable.GetUnderlyingType(target.PropertyType) :
                                                   target.PropertyType;
        }

        public static bool IsGenericList(this Type target)
        {
            return target.IsGenericType && target.GetGenericTypeDefinition() == typeof(List<>);
        }


    }
}
